import { useState, useEffect } from 'react';
import { Table, Button, Switch, Modal, Form, Input, message, Pagination } from 'antd';
import { 
  addCategory, 
  getCategory, 
  delCategory, 
  editCategory as apiEditCategory 
} from '@/api/account';

const CategoryManagement = () => {
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [form] = Form.useForm();

  // 获取分类列表
  const fetchCategories = async (page = 1) => {
    try {
      setLoading(true);
      const res = await getCategory({ currentPage: page, pageSize: 10 });
      setTableData(res.data || []);
      setTotal(res.total || 0);
    } catch (error) {
      message.error('获取分类失败');
    } finally {
      setLoading(false);
    }
  };

  // 添加/编辑分类
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      
      if (isEdit) {
        await apiEditCategory({
          ...values,
          id: form.getFieldValue('id')
        });
        message.success('更新成功');
      } else {
        await addCategory(values);
        message.success('添加成功');
      }
      
      setModalVisible(false);
      fetchCategories(currentPage);
    } catch (error) {
      if (!error.errorFields) {
        message.error('操作失败');
      }
    }
  };

  // 删除分类
  const deleteCategory = async (record) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除此分类?',
      okText: '确认',
      cancelText: '取消',
      type: 'warning',
      onOk: async () => {
        try {
          await delCategory({ id: record.id });
          message.success('删除成功');
          fetchCategories(currentPage);
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 更新状态
  const updateStatus = async (checked, record) => {
    try {
      await apiEditCategory({
        ...record,
        state: checked ? 1 : 0
      });
    } catch (error) {
      message.error('状态更新失败');
      // 恢复原来的状态
      const newData = tableData.map(item => 
        item.id === record.id ? { ...item, state: record.state } : item
      );
      setTableData(newData);
    }
  };

  // 显示编辑对话框
  const editCategory = (record) => {
    form.setFieldsValue({
      id: record.id,
      cateName: record.cateName,
      state: record.state === 1
    });
    setIsEdit(true);
    setModalVisible(true);
  };

  // 显示添加对话框
  const showAddDialog = () => {
    form.resetFields();
    setIsEdit(false);
    setModalVisible(true);
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '分类名称',
      dataIndex: 'cateName',
      key: 'cateName',
    },
    {
      title: '状态',
      key: 'state',
      width: 100,
      render: (_, record) => (
        <Switch
          checked={record.state === 1}
          onChange={(checked) => updateStatus(checked, record)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button size="small" onClick={() => editCategory(record)}>
            编辑
          </Button>
          <Button 
            size="small" 
            danger 
            onClick={() => deleteCategory(record)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  useEffect(() => {
    fetchCategories();
  }, [currentPage]);

  return (
    <div className="category-management" style={{ padding: '20px' }}>
      <h3 style={{ marginBottom: '16px' }}>商品分类管理</h3>
      
      <Button 
        type="primary" 
        onClick={showAddDialog}
        style={{ marginBottom: '20px' }}
      >
        添加分类
      </Button>
      
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        loading={loading}
        bordered
        pagination={false}
      />
      
      <Pagination
        style={{ marginTop: '20px', textAlign: 'right' }}
        total={total}
        pageSize={10}
        current={currentPage}
        onChange={(page) => setCurrentPage(page)}
        showSizeChanger={false}
      />
      
      <Modal
        title={isEdit ? '编辑分类' : '添加分类'}
        visible={modalVisible}
        onOk={submitForm}
        onCancel={() => setModalVisible(false)}
        okText="确定"
        cancelText="取消"
        width={400}
      >
        <Form form={form} labelCol={{ span: 6 }}>
          <Form.Item
            name="cateName"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="state"
            label="状态"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;